package com.shield.framework.security.authentication;

import com.shield.framework.config.ShieldConstant;
import com.shield.framework.config.ShieldSecurityProperties;
import com.shield.framework.security.auth.AuthUser;
import com.shield.framework.security.service.ShieldUserDetailsService;
import com.shield.framework.security.token.ShieldTokenService;
import com.shield.framework.security.token.ShieldTokenStore;
import com.shield.framework.utils.SecurityUtil;
import com.shield.framework.vo.TokenVo;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.StringUtil;
import net.dreamlu.mica.core.utils.WebUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: jwt token过滤器
 * @Author Andy
 */
@RequiredArgsConstructor
@Slf4j
public class ShieldAuthenticationTokenFilter extends OncePerRequestFilter {

    private final ShieldTokenService shieldTokenService;
    private final ShieldTokenStore shieldTokenStore;
    private final ShieldUserDetailsService shieldUserDetailsService;
    private final ShieldSecurityProperties properties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.info("登录 - "+request);
        // 解析 token
        String token = shieldTokenService.getToken(request);
        if (StringUtil.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }
        TokenVo tokenVo = shieldTokenStore.get(token);
        if (tokenVo == null) {
            // jwt token 解析错误 401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            WebUtil.renderJson(response, R.fail("请重新登录"));
            return;
        }
        //判断 token 是否存在
        String subject = null;

        if(properties.getTokenType().equals(ShieldConstant.TokenType.JWT)){
            try {
                subject = shieldTokenService.getSubject(token);
            } catch (JwtException | IllegalArgumentException e) {
                // jwt token 解析错误 401
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                WebUtil.renderJson(response, R.fail("请重新登录"));
                return;
            }
        }else if(properties.getTokenType().equals(ShieldConstant.TokenType.UUID)){
            subject = tokenVo.getUserName();
        }

        if (subject != null && SecurityUtil.getAuthentication() == null) {
            AuthUser authUser = (AuthUser) shieldUserDetailsService.loadUserByUsername(subject);
            //生成spring security username password Token
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser, null, authUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
